package org.huangrui.juc.source.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author hr
 * @Create 2024-04-04 17:29
 */
public class T05_ABA {
    static AtomicInteger atomicInteger = new AtomicInteger(1);
    static AtomicStampedReference<Integer> reference = new AtomicStampedReference<>(100,1);
    public static void main(String[] args) {
        new Thread(() ->{
           reference.compareAndSet(100,101,reference.getStamp(), reference.getStamp()+1);
           //暂停100毫秒
           try { TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
           reference.compareAndSet(101,100, reference.getStamp(), reference.getStamp()+1);
        },"t1").start();

        new Thread(() ->{
            int stamp = reference.getStamp();
            //暂停100毫秒
            try { TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}
            boolean b = reference.compareAndSet(100,200, stamp, stamp+1);
            System.out.println(b +"\t" + reference.getReference() +"\t" + reference.getStamp());
        },"t1").start();

    }

    private static void abaHappen() {
        new Thread(() ->{
           atomicInteger.compareAndSet(1,2);
           atomicInteger.compareAndSet(2,1);
        },"t1").start();
        //暂停200毫秒
        try { TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}
        new Thread(() ->{
            atomicInteger.compareAndSet(1,3);
             System.out.println(Thread.currentThread().getName()+"\t -----come in "+atomicInteger.get());
        },"t2").start();
    }
}
